############################
# Build Stage
############################
FROM node:20-alpine AS build

# Skip unnecessary binary downloads
ENV ELECTRON_SKIP_BINARY_DOWNLOAD=1 \
    PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
    PUPPETEER_SKIP_DOWNLOAD=1

WORKDIR /app

# Copy package-lock.json and package.json first to leverage Docker cache
COPY app/package*.json ./

# Install all dependencies including devDependencies
RUN npm ci --prefer-offline --no-audit --no-fund --legacy-peer-deps

# Copy the rest of the application code
COPY app/ .

# Accept build-time API url (default to local backend)
ARG VITE_API_BASE_URL=http://localhost:8000
ENV VITE_API_BASE_URL=${VITE_API_BASE_URL}

# Build the production-ready static site
RUN npm run build

############################
# Production Stage
############################
FROM nginx:stable-alpine AS prod

# Copy built assets
COPY --from=build /app/dist /usr/share/nginx/html

# Ensure nginx user can read static files
RUN chown -R nginx:nginx /usr/share/nginx/html \
    && find /usr/share/nginx/html -type d -exec chmod 755 {} + \
    && find /usr/share/nginx/html -type f -exec chmod 644 {} +

# Remove default nginx configuration and add minimal config
RUN rm /etc/nginx/conf.d/default.conf

# Provide minimal configuration with SPA fallback and backend proxy
RUN printf 'server {\n  listen 80;\n  server_name _;\n  root /usr/share/nginx/html;\n  index index.html;\n\n  # 设置客户端请求体大小限制为300M\n  client_max_body_size 300M;\n\n  # 后端 API 反向代理\n  location /backend/ {\n    proxy_pass http://backend:8000/;\n    proxy_set_header Host $host;\n    proxy_set_header X-Real-IP $remote_addr;\n    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n    proxy_set_header X-Forwarded-Proto $scheme;\n    proxy_read_timeout 300s;\n    proxy_connect_timeout 300s;\n    proxy_send_timeout 300s;\n    proxy_redirect http://localhost/ /backend/;\n  }\n\n  # 确保 .mjs 文件使用正确的 MIME 类型\n  location ~* \\.mjs$ {\n    default_type application/javascript;\n    add_header Cache-Control "public, max-age=31536000, immutable";\n  }\n\n  # 前端路由兜底到 index.html\n  location / {\n    try_files $uri $uri/ /index.html;\n  }\n}\n' > /etc/nginx/conf.d/site.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
